<template></template>

<script setup>
import { ref, onMounted, inject, onBeforeUnmount, watch } from 'vue';
import { DrawLine, DrawRect, DrawPolygon, DrawCircle } from '@antv/l7-draw';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';

const { map, scene } = inject('map');
let draw;
const route = useRoute();
const type = ref(route.params.type); // 使用 ref 创建响应式变量

//方式一
function initDraw(type) {
  if (draw) {
    draw.disable(); // 先禁用旧的绘图工具
  }

  switch (type) {
    case 'line': {
      draw = new DrawLine(scene, {
        distanceOptions: {},
      });
      break;
    }
    case 'rectangle': {
      draw = new DrawRect(scene, {
        distanceOptions: {},
      });
      break;
    }
    case 'polygon': {
      draw = new DrawPolygon(scene, {
        distanceOptions: {},
      });
      break;
    }
    case 'circle': {
      draw = new DrawCircle(scene, {
        distanceOptions: {},
      });
      break;
    }
    default: {
      console.log('type error');
      break;
    }
  }
  draw.enable(); // 开启绘图工具
}

onBeforeRouteUpdate(to => {
  const type = to.params.type;
  initDraw(type);
});

//方式二
// watch(
//   () => route.params.type, // 监听路由参数变化
//   newVal => {
//     type.value = newVal; // 更新响应式变量
//     // 每次类型变化时，重新处理绘图逻辑
//     if (draw) {
//       draw.disable(); // 先禁用旧的绘图工具
//     }

//     // 根据新的类型创建新的绘图工具
//     if (type.value === 'line') {
//       draw = new DrawLine(scene, { distanceOptions: {} });
//     } else if (type.value === 'rectangle') {
//       draw = new DrawRect(scene, { distanceOptions: {} });
//     } else if (type.value === 'polygon') {
//       draw = new DrawPolygon(scene, { distanceOptions: {} });
//     } else if (type.value === 'circle') {
//       draw = new DrawCircle(scene, { distanceOptions: {} });
//     }

//     draw.enable(); // 开启新的绘图工具
//   }
// );

onMounted(() => {
  map.flyTo({
    center: [114.4063, 30.465113],
    zoom: 15,
    pitch: 45,
    speed: 10,
  });
});

onBeforeUnmount(() => {
  if (draw) {
    draw.destroy(); // 销毁绘图工具
  }
});
</script>

<style scoped></style>
